package com.zdxf.conf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Administrator
 */
@EnableAsync
@Configuration
public class AsyncTaskPoolSpring implements AsyncConfigurer {
    private final static Logger logger = LoggerFactory.getLogger(AsyncTaskPoolSpring.class);

    /** 重写 spring 默认线程池，使用这种方式的好处是可以直接使用 @Async 注解 */
    /**
     * 核心线程池大小
     */
    private final int corePoolSize = 10;
    /**
     * 最大线程数
     */
    private final int maxPoolSize = 15;
    /**
     * 队列容量
     */
    private final int queueCapacity = 50;
    /**
     * 活跃时间/秒
     */
    private final int keepAliveSeconds = 60;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //队列容量
        executor.setQueueCapacity(queueCapacity);
        //活跃时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //线程名字前缀
        executor.setThreadNamePrefix("zdxf-async-task-");
        // setRejectedExecutionHandler：当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * 异步任务异常处理
     *
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> {
            logger.error("====" + throwable.getMessage() + "====", throwable);
            logger.error("exception method:" + method.getName());
        };
    }
}
